package com.thousandsunny.nosql.redis;

import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author Savitar
 */
@Service
public class RedisDistributedLockUtil {
    @Autowired
    private RedissonClient redisson;
    private static final String LOCK_PREFIX = "redis_lock_";

    public void acquire(String lockName) {
        String key = LOCK_PREFIX + lockName;
        RReadWriteLock mylock = redisson.getReadWriteLock(key);
        //lock提供带timeout参数，timeout结束强制解锁，防止死锁
        mylock.writeLock().lock(10, TimeUnit.SECONDS);
//        System.err.println("======lock======" + Thread.currentThread().getName());
    }

    public void release(String lockName) {
        String key = LOCK_PREFIX + lockName;
        redisson.getReadWriteLock(key).writeLock().unlock();
//        System.err.println("======unlock======" + Thread.currentThread().getName());
    }
}
